/*
 * @Author: chenr 526963089@qq.com
 * @Date: 2023-02-14 09:41:57
 * @LastEditors: chenr 526963089@qq.com
 * @LastEditTime: 2023-03-01 16:37:19
 * @Description: 用户数据
 */

import dayjs from 'dayjs';
import { defineStore } from 'pinia';
import { SRC_PORTAL } from '@/constants/config';
import { login, logout } from '@/api/mock';
import type { LoginParamsType, LoginHeaderType, LoginInterface } from '@/api/mock/types';

interface UserState {
  userInfo?: LoginInterface;
  access_token?: string | undefined;
  refresh_token?: string | undefined;
  user_id: string | undefined;
  time_stamp: number; // 请求返回记录时间戳
}

/**
 * @description: 用户数据存储
 * @return {*}
 */
export const useUserStore = defineStore({
  id: `${SRC_PORTAL}_user`,
  state: (): UserState => ({
    userInfo: undefined,
    access_token: undefined,
    refresh_token: undefined,
    user_id: undefined,
    time_stamp: 0,
  }),
  actions: {
    /**
     * @description: 格式化数据  不能删除是因为需要监听
     * @return {*}
     */
    removeState() {
      delete this.$state.userInfo;
      delete this.$state.access_token;
      delete this.$state.refresh_token;
      this.$state.user_id = '';
      this.time_stamp = 0;
    },

    /**
     * @description: 登陆接口
     * @param {LoginParamsType} params
     * @param {LoginHeaderType} headers
     * @return {*}
     */
    async login(params: LoginParamsType, headers?: LoginHeaderType) {
      const res = await login({ ...params }, headers);
      this.userInfo = { ...res };
      this.user_id = res.user_id;
      this.access_token = res.access_token;
      this.refresh_token = res.refresh_token;
      this.time_stamp = dayjs().unix();
      return { ...res };
    },

    /**
     * @description: 退出登录
     * @return {*}
     */
    async logout() {
      await logout();
      this.removeState();
      return true;
    },
  },
  persist: true,
});
